package com.webside.file.service;

import java.io.InputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;

@Service
public class FileService {
	@Autowired
	GridFsTemplate template;

	public void test() {
		List<GridFSDBFile> files = template.find(null);
		for (GridFSDBFile file : files) {
			System.out.println(file);
		}
	}

	public GridFSFile store(InputStream content, String filename,
			String contentType) {
		return store(content, filename, contentType, null);
	}

	public GridFSFile store(InputStream content, String filename,
			String contentType, String type) {
		return store(content, filename, contentType, type, null);
	}

	public GridFSFile store(InputStream content, String filename,
			String contentType, String type, String desc) {
		DBObject metaData = new BasicDBObject();
		if (desc != null)
			metaData.put("desc", desc);
		if (type != null)
			metaData.put("type", type);
		return template.store(content, filename, contentType);
	}

	public GridFSFile storeBanner(InputStream content, String filename,
			String contentType, String desc) {
		return store(content, filename, contentType, "image", desc);
	}

	public GridFSDBFile find(String id) {
		Criteria _criteria = Criteria.where("_id").is(id);
		Query query = Query.query(_criteria);
		return template.findOne(query);
	}
	public int delFile(String id){
		Criteria _criteria = Criteria.where("_id").is(id);
		Query query=Query.query(_criteria);
		template.delete(query);
		return 0;
	}
}
